import java.util.ArrayList;
import java.util.List;

public class AllPicks {

	public static void main(String[] args) {
		List<List<Integer>> sets = new ArrayList<List<Integer>>();
		List<Integer> set = new ArrayList<Integer>();
		set.add(1);
		set.add(2);
		set.add(3);
		sets.add(set);

		set = new ArrayList<Integer>();
		set.add(2);
		set.add(3);
		set.add(4);
		sets.add(set);

		set = new ArrayList<Integer>();
		set.add(4);
		set.add(5);
		sets.add(set);

		AllPicks ap = new AllPicks();
		ap.printAllPicks(sets);
		// ap.printAllPicksNonRecrs(sets);
	}

	public void printAllPicks(List<List<Integer>> sets) {
		if (sets == null)
			return;
		printAllPicks(sets, new int[sets.size()], 0);
	}

	public void printAllPicks(List<List<Integer>> sets, int[] elems, int level) {
		if (sets.size() == 0) {
			for (int i : elems)
				System.out.print(i + " ");
			System.out.println();
			return;
		}
		List<Integer> set = sets.get(0);
		sets.remove(0);
		for (Integer integer : set) {
			elems[level] = integer;
			printAllPicks(sets, elems, level + 1);
		}
		sets.add(0, set);
	}

	public void printAllPicksNonRecrs(List<List<Integer>> sets) {
		if (sets == null || sets.size() == 0)
			return;

		int[] ptrs = new int[sets.size()];
		int[] carriers = new int[sets.size()];
		carriers[sets.size() - 1] = 1;

		while (true) {
			for (int i = 0; i < sets.size(); ++i) {
				System.out.print(sets.get(i).get(ptrs[i]) + " ");
			}
			System.out.println();

			for (int i = sets.size() - 1; i >= 0; i--) {
				if (i != 0) {
					carriers[i - 1] = (ptrs[i] + carriers[i])
							/ sets.get(i).size();
				} else if ((ptrs[i] + carriers[i]) / sets.get(i).size() == 1)
					return;

				ptrs[i] = (ptrs[i] + carriers[i]) % sets.get(i).size();
			}
		}
	}

}
